<template>
  <div>
    <div class="shopAddress">
      <SearchBar v-if="isAdd" :buttons="buttons" @refresh="refresh" :isSearch="false"/>
      <tableList 
        :columns="tableCols"
        :isSelection="isSelection"
        :isOperates="isOperates"
        :data="tableData"
        :enableEdit="enableEdit"
        :operates="operates"
        ref="list"
        @handleSelect="handleSelect"
      />
      <div v-if="tableData.length<=0&&isAddAddress" class="addAdress" @click="toAddress">
        去添加地址
      </div>
      <pagination :pageData="pageList" @change="pageChange" />
    </div>
  </div>
</template>
<script>
import tableList from "@/components/index/tableList";
import pagination from "@/components/index/pagination";
import SearchBar from "@/components/index/SearchBar";
import { addressByUser,addAddress,deleteAddress } from "@/js/api/home"; // addressByUser
export default {
  name:'shopAddress',
  components:{
    tableList,
    SearchBar,
    pagination,
  },
  props:{
    isCheckSelect:{type:Boolean,default:()=>true},
    isSelection:{type:Boolean,default:()=>false},
    isAdd:{type:Boolean,default:()=>true},
    isOperates:{type:Boolean,default:()=>true},
    enableEdit:{type:Boolean,default:()=>true},
    isAddAddress:{type:Boolean,default:()=>false},
  },
  data(){
    return {
      tableCols: [
        { label: "姓名", prop: "consignee", edit:true },
        { label: "地址", prop: "address", edit:true },
        { label: "电话", prop: "phone", edit:true },
      ],
      tableData:[],
      selectRow:[],
      operates: {
        width: 100,
        list: [
          {
            id: "1",
            label: "删除",
            type: "text",
            show: true,
            disabled: false,
            size: "small",
            method: (index, row) => {
              this.deleteData([row.id])
            },
          },
        ],
      },
      buttons:[
        {
          label: "新增地址",
          icon: "el-icon-plus",
          size:'mini',
          type:"primary",
          method: () => {
            this.tableData.push({
              id:this.tableData.length+1,
              consignee:"",
              address:"",
              phone:""
            })
          }
        },
        {
          label: "保存",
          icon: "el-icon-plus",
          size:'mini',
          type:"primary",
          method: () => {
            this.saveData()
          }
        },
      ],
      loadNums:0,
      initIds:[],
      pageList:{pageSize:4,pageNo:1,total:10},
    }
  },
  created(){
    this.loadList()
  },
  mounted(){
    if(!this.isCheckSelect){
      this.$refs.list.$refs.tableList.toggleRowSelection(this.$refs.list.$refs.tableList.data[0],true);
    }
  },  
  methods:{
    loadList(){
      if(window.localStorage.userId){
        let obj = {
          pageNo:this.pageList.pageNo,
          pageSize:this.pageList.pageSize,
        }
        addressByUser(window.localStorage.userId,obj).then(response=>{
          if(response.data.state){
            this.tableData = response.data.data.list
            this.pageList.pageNo = response.data.data.pageNo
            this.pageList.pageSize = response.data.data.pageSize
            this.pageList.total = response.data.data.totalRecords
            this.initIds = []
            for(let i of this.tableData){
              this.initIds.push(i.id)
            }
          }else{
            if(response.data.data.list.length==0){
              this.pageList.pageNo = 1
              // this.loadList()
              // loadNums++
            }
          }
        })
      }else{
        this.tableData = []
      }
    },
    toAddress(){
      this.$router.push('/user/address')
    },
    handleSelect(selection, row){
      if (selection!=null&&selection.length > 1){
        if(!this.isCheckSelect){
          let del_row = selection.shift()
          this.$refs.list.$refs.tableList.toggleRowSelection(del_row, false) // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
        }
      }
      this.selectRow = row
      this.$emit("handleSelect",selection,row)
    },
    saveData(){ 
      let updateData = [],params={}
      for(let i of this.tableData){
        if(this.initIds.indexOf(i.id)==-1){
          updateData.push(i)
        }
      }
      params.userId = window.localStorage.userId
      params.data = JSON.stringify(updateData)
      if(updateData.length>0){
        addAddress(params).then(response=>{
          if(response.data.state){
            this.utils.tips.success(response.data.msg)
            this.loadList()
          }else{
            this.utils.tips.error(response.data.msg)
          }
        })
      }else{
        this.utils.tips.error("请新增后添加")
      }
    },
    deleteData(ids){
      if(this.isSelection){
        for(let i of ids){
          this.tableData = this.tableData.filter(item => {
            return item.id!=i
          });
        }
       this.$refs.list.clearSelect()
      }else{
        let params = {
          addressId : ids[0],
          userId:window.localStorage.userId
        }
        deleteAddress(params).then(response=>{
          if(response.data.state){
            this.utils.tips.success(response.data.msg)
            this.loadList()
          }else{
            this.utils.tips.error(response.data.msg)
          }
        })
      }
    },
    pageChange(obj){
      if(obj){
        this.pageList = obj
      }
      this.loadList()
    },
    del(){
      if(this.selectRows.length>0){
        this.utils.tips.confirm("确定要删除吗？",(val)=>{
          if(val){
            let ids = []
            for(let i of this.selectRows){
              ids.push(i.id)
            }
            this.deleteData(ids)
          }
        })
      }
    },
    refresh(){
      this.loadList()
    },
  }
}
</script>

<style lang="less">
.shopAddress{
  .is-indeterminate{
    display: none;
  }
  .addAdress{
    cursor: pointer;
    font-size: 20px;
    text-align: center;
  }
}
</style>